package com.p4.dowjones.timer;

import com.jcraft.jsch.ChannelSftp;
import com.p4.dowjones.utils.SftpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * @author Surpass
 * @Package com.p4.manage.service.dow_jones
 * @Description: 道琼斯同步下载文件
 * @date 2020/10/14 14:47
 */
@Component
public class DowJonesTimer {

    private static final Logger logger = LoggerFactory.getLogger(DowJonesTimer.class);

    private static InputStream inputStream;
    private static BufferedInputStream bi;
    private static OutputStream outputStream;
    private static BufferedOutputStream bo;

    private static int port = 22;
    private static String ip = "djrcfeed.dowjones.com";
    private static String username = "1815";
    private static String password = "Hkrtdqs123";
    private static String recordFile = "record.txt";
    private static String downloadPath = "/sanctionalert/xml/1815/";
    private static String uploadPath = "/data/hk_fxq/aml_blacklist/";
    //private static String uploadPath = "C:\\Users\\Surpass\\Desktop\\Dow\\";

    public DowJonesTimer() {
        File upload = new File(uploadPath);
        if (!upload.exists()){
            upload.mkdirs();
        }
    }

    //@Scheduled(cron = "0 0 0/4 * * ?")
    @Scheduled(cron = "0 0 * * * ?")
    public void operate(){
        logger.info("道琼斯下载文件开始");
        try {
            //sftp登录
            SftpUtil sftp = new SftpUtil(username,password, ip, port);
            sftp.login();
            logger.info("登录成功");
            //列出sftp服务器上所有文件
            Vector<ChannelSftp.LsEntry> fileVt  = (Vector<ChannelSftp.LsEntry>) sftp.listFiles(downloadPath);
            //下载记录值
            File recordTxt = new File(uploadPath+"\\"+recordFile);
            //获取需要下载的文件名集合
            List<String> downloadFileNameList = getDownloadFileName(fileVt, recordTxt);
            logger.info("需要下载的文件数量："+downloadFileNameList.size());
            //下载文件
            downloadFile(downloadFileNameList,sftp);
            logger.info("下载全部完成");
            sftp.logout();
            logger.info("sftp登出，道琼斯下载文件结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description: 根据记录值获取需要下载的文件
     * @param fileVt, 文件列表
     *        recordTxt 记录文件
     * @return java.util.List<java.lang.String>
     * @throws
     * @author Surpass
     * @date 2020/10/19 13:55
     */
    private List<String> getDownloadFileName(Vector<ChannelSftp.LsEntry> fileVt,File recordTxt) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        if (fileVt!=null&&fileVt.size()==0){
            return list;
        }

        //获取记录文件中的记录时间和全、增量标识
        Double recordData = null;
        char recordType = 0;
        String record = null;
        if (!recordTxt.exists()){
            recordTxt.createNewFile();
        }else {
            //获取记录文件中的记录值
            Reader reader = new FileReader(recordTxt);
            BufferedReader br = new BufferedReader(reader);
            record = br.readLine();
            if (record!=null&&record.trim()!=""){
                String[] split = record.split("_");
                recordData = Double.valueOf(split[0]);
                recordType = split[1].charAt(0);
            }
            if (br!=null){
                br.close();
            }
            if (reader!=null){
                reader.close();
            }
        }

        for (int i = 0; i < fileVt.size(); i++) {
            ChannelSftp.LsEntry lsEntry = fileVt.get(i);
            String fileName = lsEntry.getFilename();
            //文件过滤
            if (!fileName.endsWith(".zip")){
                continue;
            }
            String[] fileNameArr = fileName.split("_");
            Double fileData = Double.valueOf(fileNameArr[4]);
            //当有记录值的时候，下载记录值以后的所有文件
            if (StringUtils.isNotBlank(record)){
                //当前值和记录值相同
                if (fileData.equals(recordData)){
                    if ( recordType=='f' && fileNameArr[5].charAt(0)=='i' ){
                        list.add(fileName);
                    }
                }
                if (fileData>recordData){
                    list.add(fileName);
                }
            }
            //当没有记录值的时候，只下载最新的全量(当倒数第二个是全量，那么直接跳出循环)
            if (StringUtils.isBlank(record)){
                if (i==fileVt.size()-2&&fileNameArr[5].charAt(0)=='f'){
                    list.add(fileName);
                    break;
                }
                if (i==fileVt.size()-1&&fileNameArr[5].charAt(0)=='f'){
                    list.add(fileName);
                }
            }
        }
        return list;
    }


    /**
     * @Description: TODO
     * @param downloadFileNameList 文件名下载集合
     *        sftp
     * @return void
     * @throws
     * @author Surpass
     * @date 2020/10/19 13:56
     */
    private void downloadFile(List<String> downloadFileNameList, SftpUtil sftp) {
        int flag = 0;
        try {
            for (String fileName : downloadFileNameList) {
                byte[] download = sftp.download(downloadPath, fileName);
                logger.info("文件下载完成"+fileName);
                //下载文件输入流
                inputStream = new ByteArrayInputStream(download);
                bi = new BufferedInputStream(inputStream);
                //下载文件输出流
                outputStream = new FileOutputStream(uploadPath+fileName);
                bo = new BufferedOutputStream(outputStream);
                byte[] bytes = new byte[1024*4];
                int len = 0;
                while ( (len = bi.read(bytes))!=-1){
                    bo.write(bytes,0,len);
                }
                //下载位置标识 record 输出流
                outputStream = new FileOutputStream(uploadPath+recordFile);
                bo = new BufferedOutputStream(outputStream);
                System.out.println(fileName.substring(16, 30));
                bytes = fileName.substring(16, 30).getBytes();
                bo.write(bytes);
                logger.info("当前位置记录值写入:"+fileName.substring(16, 30));
                ++flag;
                logger.info("保存完成，当前下载数：{}，剩余下载：{}",flag,downloadFileNameList.size()-flag);
            }
        }catch (Exception e){
            logger.info("下载失败",e);
        }finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
                if(bo!=null){
                    bo.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.info("输入流关闭异常",e);
            }
        }
    }
}
